#include "RegisterDialog.h"
#include "ui_RegisterDialog.h"
#include "DatabaseManager.h"
#include <QMessageBox>
#include <QCryptographicHash>
#include <QRegularExpression>
#include <QDebug>

RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog),
    m_registeredUsername("")
{
    ui->setupUi(this);
    setWindowTitle("鲜花销售系统 - 注册");

    // 设置密码框的显示模式
    ui->passwordEdit->setEchoMode(QLineEdit::Password);
    ui->confirmPasswordEdit->setEchoMode(QLineEdit::Password);

    // 连接信号槽
    connect(ui->usernameEdit, &QLineEdit::textChanged,
            this, &RegisterDialog::checkUsernameAvailability);
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::checkUsernameAvailability()
{
    QString username = ui->usernameEdit->text().trimmed();

    if(username.isEmpty()) {
        ui->usernameLabel->clear(); // 修改为 usernameLabel
        return;
    }

    // 用户名格式校验
    QRegularExpression regex("^[a-zA-Z0-9_]{4,20}$");
    if(!regex.match(username).hasMatch()) {
        ui->usernameLabel->setText("<font color='red'>用户名格式不符</font>"); // 修改为 usernameLabel
        return;
    }

    // 检查用户名是否已存在
    QSqlQuery query;
    query.prepare("SELECT user_id FROM login_users WHERE username = :username");
    query.bindValue(":username", username);

    if(!query.exec()) {
        ui->usernameLabel->setText("<font color='red'>查询失败</font>"); // 修改为 usernameLabel
        qDebug() << "数据库查询错误:" << query.lastError();
        return;
    }

    // 更新标签显示
    ui->usernameLabel->setText( // 修改为 usernameLabel
        query.next() ?
        "<font color='red'>用户名已存在</font>" :
        "<font color='green'>用户名可用</font>"
    );
}

void RegisterDialog::on_registerButton_clicked()
{
    // 获取输入值
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();
    QString confirmPassword = ui->confirmPasswordEdit->text();

    // 输入验证
    if(username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名和密码不能为空");
        return;
    }

    if(password != confirmPassword) {
        QMessageBox::warning(this, "警告", "两次密码输入不一致");
        return;
    }

    if(password.length() < 6) {
        QMessageBox::warning(this, "警告", "密码长度需≥6位");
        return;
    }

    // 最终用户名检查
    QSqlQuery checkQuery;
    checkQuery.prepare("SELECT user_id FROM login_users WHERE username = :username");
    checkQuery.bindValue(":username", username);

    if(!checkQuery.exec()) {
        QMessageBox::critical(this, "错误", "数据库查询失败");
        qDebug() << "查询错误:" << checkQuery.lastError();
        return;
    }

    if(checkQuery.next()) {
        QMessageBox::warning(this, "警告", "用户名已被注册");
        return;
    }

    // 密码加密
    QByteArray passwordHash = QCryptographicHash::hash(
        password.toUtf8(),
        QCryptographicHash::Md5
    );
    QString encryptedPassword = passwordHash.toHex();

    // 插入数据库
    QSqlQuery insertQuery;
    insertQuery.prepare(
        "INSERT INTO login_users (username, password, user_type) "
        "VALUES (:username, :password, 'user')"
    );
    insertQuery.bindValue(":username", username);
    insertQuery.bindValue(":password", encryptedPassword);

    if(!insertQuery.exec()) {
        QMessageBox::critical(this, "错误", "注册失败");
        qDebug() << "插入错误:" << insertQuery.lastError();
        return;
    }

    // 注册成功处理
    m_registeredUsername = username;
    qDebug() << "注册成功:" << username;

    QMessageBox::information(this, "成功", "注册成功！");
    accept();
}
